package make

import (
	"github.com/runningwater/gohub/pkg/app"
	"github.com/runningwater/gohub/pkg/console"
	"github.com/spf13/cobra"
)

var CmdMakeMigration = &cobra.Command{
	Use:   "migration",
	Short: "Create a migration file, example: make migration add_users_table",
	Run:   runMakeMigration,
	Args:  cobra.ExactArgs(1), // 只允许且必须传 1 个参数
}

func runMakeMigration(cmd *cobra.Command, args []string) {
	// 格式：2023_01_30_141939_create_users_table.go
	timeStr := app.TimenowInTimezone().Format("2006_01_02_150405")
	// 第二个参数是迁移名称，用于生成迁移文件的文件名
	model := makeModelFromString(args[0])
	fileName := timeStr + "_" + model.PackageName
	// 拼接生成的迁移文件的路径
	filePath := "database/migrations/" + fileName + ".go"
	// 基于 tpls 目录创建文件
	createFileFromTpl(filePath, "migration", model, map[string]string{"{{FileName}}": fileName})

	// 输出信息
	console.Success("Migration file created, after modify it, use `migrate up` to migrate database.")
}
